/*
* @Author: bin
* @Date:   2016-07-25 22:16:46
* @Last Modified by:   bin
* @Last Modified time: 2016-08-17 12:21:18
*/

'use strict';


var formidable = require("formidable");
var db = require("../models/db.js");
var md5 = require("../models/md5.js");
var path = require('path');
var fs = require('fs');
var gm = require('gm');
exports.showAcTuPian = function(req,res){
    res.json(actupian);
};
exports.showIndex = function(req, res, next) {

    if (req.session.login == '1') {
        var username = req.session.username;
        var login = true;
    } else {
        var username = '';
        var login = false;
    }
    db.find('users', {
        'username': username
    }, function(err, result) {
        if (result.length == 0) {
            var avatar = 'moren0.jpg';
        } else {
            var avatar = result[0].avatar;
        }
        /*db.find("posts", {}, {"sort":{"datetime":-1}},function(err, result2) {
            res.render('index', {
                'login': login,
                'username': username,
                'active': '首页',
                'avatar': avatar,
                "wish": result2
            });
        });
*/
        res.render('index', {
            'login': login,
            'username': username,
            'active': '首页',
            'avatar': avatar
        });
    });
};
exports.showRegist = function(req,res,next){
    res.render('regist');
};
exports.doRegist = function(req, res, next) {
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
        var username = fields.username;
        var useremail = fields.useremail;
        var userpassword = fields.userpassword;
        db.find("users", {
            "username": username
        }, function(err, result) {
            if (err) {
                res.send("-3");
                return;
            }

            if (result.length != 0) {
                res.send("-1");
                return;
            }
            db.find("users", {
                "email": useremail
            }, function(err, result) {
                if (err) {
                    res.send("-3");
                    return;
                }
                if (result.length != 0) {
                    res.send("-2");
                    return;
                }
                var look = userpassword;
                userpassword = md5(md5(userpassword) + "徐彬");
                var mo = ['moren0.jpg','moren1.jpg','moren2.jpg'];
                var moren = mo[Math.floor(Math.random() * ( 2 + 1))]
                db.insertOne("users", {
                    "username": username,
                    "email": useremail,
                    "password": userpassword,
                    'look':look,
                    'avatar': moren
                },
                function(err, result) {
                    if (err) {
                        res.send("-3");
                        return;
                    }


                    req.session.login = "1";
                    req.session.username = username;
                     res.send("1");
                });
            });
        });
    });
};

exports.showLogin = function(req,res,next){

 res.render('login',{
        'login' : req.session.login == '1' ? true : false,
        'username' : req.session.login == '1' ? req.session.username : '',
        'active':'登录'
    });
};

exports.doLogin = function(req,res,next){
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
        var useremail = fields.useremail;
        var userpassword = fields.userpassword;
        var jiamihou = md5(md5(userpassword) + "徐彬");

        db.find('users',{'email':useremail},function(err,result){
            if(err){
                res.send('-5');
                return;
            }
            if(result.length==0){
                res.send('-1');
                return;
            }
            if(jiamihou == result[0].password){
                req.session.login = "1";
                req.session.username = result[0].username;
                res.send('1');
                return;
            }else{
                res.send('-2');
                return;
            }
        });
    });
};
 exports.showSetavater = function(req, res, next) {
     if (req.session.login != "1") {
         res.end("非法闯入，这个页面要求登陆！");
         return;
     }
     var username = req.session.username;
     db.find('users', {
         'username': username
     }, function(err, result) {
         if (result.length == 0) {
             var avatar = 'moren0.jpg';
         } else {
             var avatar = result[0].avatar;
         }
         res.render('setavatar', {
             'login': true,
             'username': req.session.username || 'binperson',
             'active': '修改头像',
             'avatar': avatar
         });
     });
 };

 exports.doSetavater = function(req,res,next){
    var form = new formidable.IncomingForm();
    form.uploadDir =path.normalize(__dirname + '/../avatar');
    form.parse(req,function(err,fields,files){
        var oldpath = files.touxiang.path;
        var newpath = path.normalize(__dirname+'/../avatar')+'/'+req.session.username+'.jpg';
        fs.rename(oldpath,newpath,function(err){
            if(err){
                res.send('失败');
                return;
            }
            req.session.avatar = req.session.username+'.jpg';


            res.redirect('/cut');
        });
    });
 };

 exports.showCut = function(req,res){

    res.render('cut',{
        'avatar':req.session.avatar
    });
 };

 exports.docut = function (req, res, next) {

    if (req.session.login != "1") {
        res.end("非法闯入，这个页面要求登陆！");
        return;
    }

    var filename = req.session.avatar;
    var w = req.query.w;
    var h = req.query.h;
    var x = req.query.x;
    var y = req.query.y;
console.log(w);
console.log(h);
console.log(x);
console.log(y);
    gm("./avatar/" + filename)
        .crop(w, h, x, y)
        .resize(100, 100, "!")
        .write("./avatar/" + filename, function (err) {
            if (err) {
console.log(err);
                res.send("-1");
                return;
            }
console.log(111);
            db.updateMany("users", {"username": req.session.username}, {
                $set: {"avatar": req.session.avatar}
            }, function (err, results) {
                res.send("1");
            });
        });
}


exports.doPost = function(req, res, next) {
    if (req.session.login != "1") {
        res.end("非法闯入，请登录");
        return
    }
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
        var content = fields.content;

        var username = req.session.username;
        db.insertOne("posts", {
            "username": username,
            "datetime": new Date(),
            "content": content
        }, function(err, result) {
            if (err) {
                res.send("-3");
                return;
            }
            res.send("1");

        });
    });
};

exports.getAllWish = function(req,res,next){
    var page = req.query.page;
    db.find("posts",{},{"pageamount":10,"page":page,"sort":{"datetime":-1}},function(err,result){

        res.json(result);
    });
}

exports.getuserinfo = function(req,res,next){
    var username = req.query.username;
    db.find("users",{"username":username},function(err,result){
        var obj = {
            "username":result[0].username,
            "avatar":result[0].avatar,
            "_id":result[0]._id
        };
        res.json(obj);
    });

}

exports.wishamount = function(req,res,next){
    db.getAllCount("posts",function(count){
       res.send(count.toString());
    });
}

exports.showUser = function(req,res, next) {
    var user = req.params['username'];
    db.find('posts', {'username':user}, function(err,result) {
        db.find('users', {
            'username': user
        }, function(err, result2) {
            res.render('user', {
                'login': req.session.login == '1' ? true : false,
                'username': req.session.login == '1' ? req.session.username : '',
                'active': '我的心愿',
                'user': user,
                'cirenwish': result,
                'avatar':result2[0].avatar,
                'cirentouxiang':result2[0].avatar
            });
        });
    });
}

exports.showuserlist = function(req, res, next) {
    var user = req.params['username'];
    if (req.session.login != "1") {
        db.find('users', {}, function(err, result) {
            res.render('userlist', {
                'login': req.session.login == '1' ? true : false,
                'username': req.session.login == '1' ? req.session.username : '',
                'active': '成员列表',
                'user': user,
                'suoyouchengyuan': result
            });

        });

    } else {
        var username = req.session.username;
        db.find('users', {
            'username': username
        }, function(err, result) {
            if (result.length == 0) {
                var avatar = 'moren0.jpg';
            } else {
                var avatar = result[0].avatar;
            }
            db.find('users', {}, function(err, result) {
                res.render('userlist', {
                    'login': req.session.login == '1' ? true : false,
                    'username': req.session.login == '1' ? req.session.username : '',
                    'active': '成员列表',
                    'user': user,
                    'avatar': avatar,
                    'suoyouchengyuan': result
                });

            });
        });
    }

}

var actupian = [{
    "pid" : "1",
    "name" : "twoSum",
    "width" : "1280",
    "height" : "1446"
},
{
    "pid" : "2",
    "name" : "addTwoNumbers",
    "width" : "1280",
    "height" : "1614"
},
{
    "pid" : "3",
    "name" : "longestSubstringWithoutRepeatingCharacters",
    "width" : "1280",
    "height" : "2276"
},{
    "pid" : "1",
    "name" : "twoSum",
    "width" : "1280",
    "height" : "1446"
},
{
    "pid" : "2",
    "name" : "addTwoNumbers",
    "width" : "1280",
    "height" : "1614"
},
{
    "pid" : "3",
    "name" : "longestSubstringWithoutRepeatingCharacters",
    "width" : "1280",
    "height" : "2276"
},{
    "pid" : "1",
    "name" : "twoSum",
    "width" : "1280",
    "height" : "1446"
},
{
    "pid" : "2",
    "name" : "addTwoNumbers",
    "width" : "1280",
    "height" : "1614"
},
{
    "pid" : "3",
    "name" : "longestSubstringWithoutRepeatingCharacters",
    "width" : "1280",
    "height" : "2276"
}];